<?php
/**
 * 净水器模型
 *
 */
namespace Admin\Model;
use Think\Model;
use Think\Log;
class WaterPurifierModel extends BaseModel{

	protected $receive = array(
		'actually_price'=>'净水器',
		'activity_price'=>'净水器活动价',
		'activity_day'=>'活动时间',
		'deliver_price'=>'上门送货费',
		'install_price'=>'现场安装费',
		'description'=>'活动说明');

	protected $orderType = array(1=>'领取', 2=>'更换', 3=>'维修');
	protected $payment = array(1=>'支付宝',2=>'微信',3=>'安装后付款');
	protected $brand = array(1=>'美的', 2=>'展纯', 3=>'千千泉');
	/**
	 * 获取净水器配置
	 * @param  string  $like 过滤参数
	 * @param int $type 净水器类型
	 * @return  
	 */
	public function getConfig($like = '', $brand = 0)
	{
		$map['is_deleted'] = 0;
		if ($like) {
			$map['config_key'] = array('LIKE', '%'.$like.'%'); 
		}
		if ($brand) {
			$map['brand'] = $brand;
		}
		$res = $this->where($map)->order('config_key asc')->select();
		if (!$res) {
			return array();
		}
		$data = array();
		foreach ($res as $v) {
			$this->format($v, $data);
		}
		return $data;
	}


	public function format($config, &$return)
	{ 
		if(strpos($config['config_key'], 'introduce') !== false){ //产品介绍
			if(strpos($config['config_key'], 'cover_pic')){
				$return['cover_pic'] = $config['url'];
			}elseif(strpos($config['config_key'], 'pic')){
				$return['pics'][] = $config['url'];
			}else{
				$return['tel'] = $config['url'];
			}
		}elseif(strpos($config['config_key'], 'receive') !== false){ //领取
			if(strpos($config['config_key'], 'price')){
				//$return[$config['config_key']] = $config['price'];
				$return[$config['config_key']] = array('name'=>$config['config_value'],'price'=>$config['price']);
			}elseif(strpos($config['config_key'], 'day') !== false){
				$return[$config['config_key']] = $config['day'];
			}else{
				$return[$config['config_key']] = $config['config_value'];
			}
		}else{   //更换与维修
			if (strpos($config['config_key'], 'item')) {
				$item['name'] = $config['config_value'];
				$item['day'] = $config['day'];
				$item['price'] = $config['price'];
				$item['status'] = $config['status'];
				$return['item'][] = $item; 
			}else{
				$return[$config['config_key']]['name'] 	= $config['config_value'];
				$return[$config['config_key']]['day'] 	= $config['day'];
				$return[$config['config_key']]['price'] = $config['price'];
				$return[$config['config_key']]['status']= $config['status'];
			}

		}
	}

	/**
	 * 新增产品介绍
	 * @param string $coverPic 封面图
	 * @param array $pics     产品介绍图
	 * @param int $adminId  管理员
	 * @param int $type 净水器类型
	 */
	public function addIntroduce($coverPic, $pics, $tel, $adminId, $brand)
	{
		if(!$coverPic){
			$this->setErrMsg(10001, '产品图片不能为空');
			return false;
		}
		if(strpos($coverPic, 'http') !== 0){
			$this->setErrMsg(10001, '产品图片错误');
			return false;
		}
		if(!is_array($pics) or empty($pics)){
			$this->setErrMsg(10001, '产品介绍图片错误');
			return false;
		}
		if (count($pics) > 6) {
			$this->setErrMsg(10001, '产品介绍图片过多');
			return false;
		}
		if ($tel == '') {
			$this->setErrMsg(10001, '服务电话错误');
			return false;
		}
		if (!in_array($brand, array(1, 2, 3))){
			$this->setErrMsg(10001, '净水器类型参数错误');
			return false;
		}

		$data['config_key'] = 'introduce_cover_pic';
		$data['config_value'] = '产品封面';
		$data['url'] = $coverPic;
		$data['add_time'] = time();
		$data['admin_id'] = $adminId;
		$data['is_deleted'] = 0;
		$data['brand'] = $brand;

 		$dataList[] = $data;
 		$data['config_key'] = 'introduce_tel';
		$data['config_value'] = '服务电话';
		$data['url'] = $tel;
		$data['add_time'] = time();
		$data['admin_id'] = $adminId;
		$data['is_deleted'] = 0;
		$data['brand'] = $brand;
 		$dataList[] = $data;
		foreach ($pics as $k => $v) {
			$data['config_key'] = 'introduce_pic'.$k;
			$data['config_value'] = '产品介绍图'.($k+1);
			if(strpos($v, 'http') !== 0){
				$this->setErrMsg(10001, '产品图片'.($k+1).'错误');
				return false;
			}
			$data['url'] = $v;
			$data['add_time'] = time();
			$data['admin_id'] = $adminId;
			$data['is_deleted'] = 0;
			$data['brand'] = $brand;
			$dataList[] = $data; 	
		} 
		$map['config_key'] = array('LIKE', '%introduce%');
		$map['brand'] = $brand;
		$this->startTrans();
		
		$update = $this->where($map)->save(array('is_deleted'=>1));
		$res = $this->addAll($dataList, array(), true);
		if ($res and $update !== false) {
			$this->commit();
			return $res;
		}else{
			$this->rollback();
			$this->setErrMsg(50000, '新增产品介绍失败');
			return false;
		}
	}
	
	/**
	 * 新增领取配置
	 * @param array $data    配置数据
	 * @param int $adminId 管理员
	 * @param int $brand 净水器类型
	 */
	public function addReceive($data,$adminId, $brand)
	{
		$rules = array(
			array('actually_name', 'require', '请输入净水器名称',1),
			array('actually_price', '/^\d+(\.\d{1,2})?$/', '净水器价格设置错误',1,'regex',1),
			array('activity_price', '/^\d+(\.\d{1,2})?$/', '活动价格设置错误',1,'regex',1),
			array('activity_day', '/^\d+(\.\d{1,2})?$/', '活动天数设置错误',1,'regex',1),
			array('deliver_name', 'require', '请输入上门送货费名称',1),
			array('deliver_price', '/^\d+(\.\d{1,2})?$/', '上门送货费设置错误',1,'regex',1),
			array('install_name', 'require', '请输入现场安装费名称',1),
			array('install_price', '/^\d+(\.\d{1,2})?$/', '现场安装费设置错误',1,'regex',1),
			array('description', 'require', '请输入活动说明',1),
			array('description', '1,100', '活动说明长度不对', 1, 'length'),
			);
		$vali = $this->validate($rules)->create();
		if ($vali === false) {
			$this->setErrMsg(10001, $this->getError());
			return false;
		}
		if(!in_array($brand, array(1,2,3))){
			$this->setErrMsg(10002,'净水器类型参数错误');
			return false;
		}
		$dataList = array();
		foreach ($data as $k => $v) {
			$insert = array();
			if(strpos($k, 'name') === false){
				$insert['config_key'] = 'receive_'.$k;
				$insert['admin_id'] = $adminId;
				$insert['add_time'] = time();
				$key = str_replace('price', 'name', $k);
				if (isset($data[$key])) {
					$insert['config_value'] = $data[$key];
				}else{
					$insert['config_value'] = $this->receive[$k];
				}
				if($k == 'activity_day'){
					$insert['price'] = 0;
					$insert['day'] = $v;
				}else{
					$insert['price'] = $v;
					$insert['day'] = 0;
				}
				$insert['brand'] = $brand;
				$dataList[] = $insert;
			}
		}
		$res = $this->addAll($dataList, array(), true);
		if ($res) {
			return $res;
		}else{
			$this->setErrMsg(50000, '新增领取配置失败');
			return false;
		}
	}

	/**
	 * 新增更换配置
	 * @param array $service     服务费数组
	 * @param array $configs      更换项目数组
	 * @param int $adminId      管理员
	 * @param int $brand 净水器类型 
	 */
	public function addReplace($service, $configs, $adminId, $brand)
	{
		//Log::write(var_export($configs, true), 'config');exit;
		if (!isset($service['name']) or $service['name'] === '') {
			$this->setErrMsg(10001, '请填写服务费名');
			return false;
		}
		if (!isset($service['price']) or $service['price'] < 0) {
			$this->setErrMsg(10001, '服务费设置错误');
			return false;
		}
		if (!isset($service['suggest_day']) or $service['suggest_day'] <= 0) {
			$this->setErrMsg(10001, '建议更换时间错误');
			return false;
		}
		if(!is_array($configs) or empty($configs)){
			$this->setErrMsg(10001, '更换项目设置错误');
			return false;
		}
		if (count($configs) > 10) {
			$this->setErrMsg(10001, '更换项目过多');
			return false;
		}
		if (!in_array($brand, array(1,2,3))) {
			$this->setErrMsg(10001, '净水器类型参数错误');
			return false;
		}
		$dataList = array(array('config_value'=>$service['name'],
			                    'price'=>$service['price'],
			                    'day'=>0,
			                    'status'=>1,
			                    'config_key'=>'replace_service_price',
			                    'add_time'=>time(),
			                    'admin_id'=>$adminId,
			                    'is_deleted'=>0,
			                    'brand'=>$brand));
		$dataList[] = array('config_value'=>'建议更换时间',
			                    'price'=>0,
			                    'day'=>$service['suggest_day'],
			                    'status'=>1,
			                    'config_key'=>'replace_suggest_day',
			                    'add_time'=>time(),
			                    'admin_id'=>$adminId,
			                    'is_deleted'=>0,
			                    'brand'=>$brand);
		foreach ($configs as $k => $v) {
			$data = $this->checkReplaceData($v);
			if (!$data) {
				return false;
			}
			$data['config_key'] = 'replace_item'.$k;
			$data['add_time'] = time();
			$data['admin_id'] = $adminId;
			$data['is_deleted'] = 0;
			$data['brand'] = $brand;
			$dataList[] = $data;
			unset($data);
		}
		//每次保存数据先删除旧数据
		$map['config_key'] = array('LIKE', 'replace%');
		$map['brand'] = $brand;
		$delete = array('is_deleted' => 1);
		$this->startTrans();
		$update = $this->where($map)->save($delete);

		$res = $this->addAll($dataList, array(), true);
		if ($res and $update !== false) {
			$this->commit();
			return $res;
		}else{
			$this->rollback();
			$this->setErrMsg(50000, '新增更换配置失败');
			return false;
		}
	}

	/**
	 * 检查更换项目数据
	 * @param  array $data 需要检查的数据
	 * @return mixed       
	 */
	public function checkReplaceData($data)
	{
		$name = trim($data['name']);
		if ($name === '') {
			$this->setErrMsg(10001, '更换项目名称不能为空');
			return false;
		}
		$price = number_format($data['price'], 2);
		if ($price < 0) {
			$this->setErrMsg(10001, '更换项目费用设置错误');
			return false;
		}
		$day = 0;
		// $day = intval($data['day']);
		// if ($day <= 0) {
		// 	$this->setErrMsg(10001, '更换项目时间间隔错误');
		// 	return false;
		// }
		if(!isset($data['status']) or !in_array($data['status'], array(0, 1))){
			$this->setErrMsg(10001, '更换项目状态错误');
			return false;
		}
		$newData['config_value'] = $name;
		$newData['price'] = $price;
		$newData['day'] = $day;
		$newData['status'] = $data['status'];
		return $newData;
	}

	/**
	 * 新增维修配置
	 * @param array $repairPrice 维修费用数组
	 * @param array $configs     维修项目数组
	 * @param int $adminId     管理员
	 * @param int $brand 净水器类型
	 */
	public function addRepair($repair, $configs, $adminId, $brand)
	{
		if (!isset($repair['name']) or $repair['name'] === '') {
			$this->setErrMsg(10001, '请填写维修费名');
			return false;
		}
		if (!isset($repair['price']) or $repair['price'] < 0) {
			$this->setErrMsg(10001, '维修费设置错误');
			return false;
		}
		
		if (!is_array($configs) or empty($configs)){
			$this->setErrMsg(10001, '维修项目设置错误');
			return false;
		}
		if (count($configs) > 10) {
			$this->setErrMsg(10001, '维修项目过多');
			return false;
		}
		if (!in_array($brand, array(1, 2, 3))){
			$this->setErrMsg(10001, '净水器类型参数错误');
			return false;
		}
		$dataList = array(array('config_value'=>$repair['name'],
			                    'price'=>$repair['price'],
			                    'status'=>1,
			                    'config_key'=>'repair_repair_price',
			                    'add_time'=>time(),
			                    'admin_id'=>$adminId,
								'is_deleted'=>0,
								'brand'=>$brand));
		foreach ($configs as $k => $v) {
			$data = $this->checkRepairData($v);
			if (!$data) {
				return false;
			}
			$data['config_key'] = 'repair_item'.$k;
			$data['add_time'] = time();
			$data['admin_id'] = $adminId;
			$data['is_deleted'] = 0;
			$data['brand'] = $brand;
			$dataList[] = $data;
			unset($data);
		}
		//Log::write(var_export($dataList, true), 'dataList');
		//return false;
		//每次保存数据先删除旧数据
		$map['config_key'] = array('LIKE', 'repair%');
		$map['brand'] = $brand;
 		$delete = array('is_deleted' => 1);
		$update = $this->where($map)->save($delete);

		$res = $this->addAll($dataList, array(), true);
		if ($res) {
			return $res;
		}else{
			$this->setErrMsg(50000, '新增维修配置失败');
			return false;
		}
	}

	/**
	 * 检查维修项目数据
	 * @param  array $data 需要检查的数据
	 * @return mixed       
	 */
	public function checkRepairData($data)
	{
		$name = trim($data['name']);
		if ($name === '') {
			$this->setErrMsg(10001, '维修项目名称不能为空');
			return false;
		}
		$price = number_format($data['price'],2);
		if ($price < 0) {
			$this->setErrMsg(10001, '维修项目费用设置错误');
			return false;
		}
		
		if(!isset($data['status']) or !in_array($data['status'], array(0, 1))){
			$this->setErrMsg(10001, '维修项目状态错误');
			return false;
		}
		$newData['config_value'] = $name;
		$newData['price'] = $price;
		$newData['status'] = $data['status'];
		return $newData;
	}

	/**
	 * 订单列表
	 * @param  array $data 查询条件
	 * @return mixed       
	 */
	public function orderList($data, $down = false)
	{
		$model = M('WaterPurifierOrder');
		$model->alias('o');
		$map['o.is_deleted'] = 0;
		$map['o.pay_time'] = array('gt', 0);
		if (isset($data['start']) and $data['start'] !== '') {
			$map['o.add_time'][] = array('egt', strtotime($data['start'].' 00:00:00'));
		}
		if (isset($data['end']) and $data['end'] !== '') {
			$map['o.add_time'][] = array('elt', strtotime($data['end'].' 23:59:59'));
		}
		if (isset($data['order_type']) and in_array($data['order_type'], array(1, 2, 3))) {
			$map['o.order_type'] = $data['order_type'];
		}
		if (isset($data['day']) and $data['day'] > 0) {
			$day = intval($data['day']);
			$today = strtotime(date('Y-m-d').' 23:59:59');
			$map['o.finish_time'][] = array('elt', strtotime('-'.$day.' day', $today));
			$map['o.finish_time'][] = array('gt', 0);
		}

		if (isset($data['province']) and $data['province']) {
			$map['o.province'] = $data['province'];
		}

		if (isset($data['city']) and $data['city']) {
			$map['o.city'] = $data['city'];
		}

		if (isset($data['user_id']) and $data['user_id'] > 0) {
			$map['o.user_id'] = $data['user_id'];
		}
		if (isset($data['pay_status']) and in_array($data['pay_status'], array(1,2))) {
			if($data['pay_status'] == 1){   //正常订单金额
				$map['order_status'] = 1;
			}else{   //取消订单金额
				$map['order_status'] = 0;
			}
		}

		if (isset($data['brand']) and in_array($data['brand'], array(1,2,3))) {
			$map['o.brand'] = $data['brand'];
		}

		if (isset($data['keyword']) and $data['keyword'] !== '') {
			$model->join('__USER__ u ON u.user_id = o.user_id', 'LEFT');
			$or['o.order_num'] = array('LIKE', '%'.$data['keyword'].'%');
			$or['o.shipping_name'] = array('LIKE', '%'.$data['keyword'].'%');
			$or['o.shipping_tel'] = array('LIKE', '%'.$data['keyword'].'%');
			$or['o.shipping_addr'] = array('LIKE', '%'.$data['keyword'].'%');
			$or['u.user_name'] = array('LIKE', '%'.$data['keyword'].'%');
			$or['_logic'] = 'or';
			$map['_complex'] = $or;
		}
		

		$total = $model->where($map)->count();
		$pageSize = $data['page_size'] > 0 ? $data['page_size'] : 10;
		$pageIndex = $data['page'] > 0 ? $data['page'] : 1;
		$page = pagination($total, $pageSize ,$pageIndex);
		if ($total > 0) {
			if ($down) {
				$list = $model->alias('o')->field('o.*,u.user_name')
			       	  ->join('__USER__ u ON u.user_id = o.user_id', 'LEFT')
			       	  ->where($map)->order('o.add_time desc')->select();
			}else{
				$list = $model->alias('o')->field('o.*,u.user_name')
			       	  ->join('__USER__ u ON u.user_id = o.user_id', 'LEFT')
			          ->where($map)->order('o.add_time desc')
			          ->limit($page['offset'], $page['limit'])->select();
			}
			foreach ($list as $k => $v) {
				$list[$k]['status'] = $v['finish_time'] ? '服务完成' : '服务中';
				if ($v['cancel_time']) {
					$list[$k]['status'] = '已取消';
				}
				$list[$k]['add_time'] = date('Y-m-d H:i', $v['add_time']);
				$v['pay_time'] and $list[$k]['pay_time'] = date('Y-m-d H:i', $v['pay_time']);
				if($v['finish_time']) {
					$list[$k]['finish_time'] = date('Y-m-d H:i', $v['finish_time']);
				}else{
					$list[$k]['finish_time'] = '';
				}
				$list[$k]['order_type'] = $this->orderType[$v['order_type']];
				$list[$k]['payment_text'] = $v['payment_status'] == 0 ? '未付款' : '已付款';
				$list[$k]['shipping_addr'] .= $v['doorplate'];
				$list[$k]['brand'] = $this->brand[$v['brand']];
			}
			return array('data'=>$list, 'page'=>$page);
		}
		return array('data'=>array(), 'page'=>$page);
	}

	public function getOrderInfo($orderId)
	{
		$order = M('WaterPurifierOrder')->find($orderId);
		if (!$order) {
			$this->setErrMsg(20001, '查找不到对应的订单信息');
			return false;
		}
		$detailModel = M('WaterPurifierOrderDetail');
		$map['order_id'] = $order['order_id'];
		$map['is_deleted'] = 0;
		$map['reduce'] = 0;
		$detail = $detailModel->where($map)->select();
		$order['detail'] = $detail;
		// $map['reduce'] = array('gt', 0);
		// $order['reduce'] = $detailModel->where($map)->sum('reduce');
		$log = array();
		if ($order['cancel_time']) {
			$order['service_status'] = 2;
			$order['service_status_text'] = '已取消';
		}elseif($order['finish_time']){
			$order['service_status'] = 1;
			$order['service_status_text'] = '已完成';
		}else{
			$order['service_status'] = 0;
			$order['service_status_text'] = '待服务';
		}
		$order['add_time'] = date('Y年m月d日 H:i:s', $order['add_time']);
		$order['shipping_addr'] .= $order['doorplate'];
		$logData['time'] = $order['add_time'];
		$logData['type'] = '订单提交成功';
		$logData['content'] = '客服将会在72小时内联系您，指派师傅上门安装';
		$logData['is_cancel'] = false;
		$log[] = $logData;
		if ($order['finish_time']) {
			$order['finish_time'] = date('Y年m月d日 H:i:s', $order['finish_time']);
			$logData['time'] = $order['finish_time'];
			$logData['type'] = '安装完成';
			$handler = $order['finish_type'] == 2 ? '管理员' : '业主';
			$logData['content'] = $handler.'已进行了确认完成订单的操作';
			$logData['is_cancel'] = false;
			$log[] = $logData;
		}
		if ($order['cancel_time']) {
			$order['cancel_time'] = date('Y年m月d日 H:i:s', $order['cancel_time']);
			$logData['time'] = $order['cancel_time'];
			$logData['type'] = '取消订单';
			$logData['content'] = '订单已经取消，客户人员已经提交了凭证';
			$logData['is_cancel'] = true;
			$log[] = $logData;
		}
		$order['log'] = $log;
		if ($order['payment_status'] == 1) {
			if($order['payment_code'] <= 2){
				$order['payment_type'] = '线上支付';
			}else{
				//获取实际支付方式 
				$payModel = M('UserPayRecord');
				$payMap['order_id'] = $order['order_num'];
				$payRecord = $payModel->where($payMap)->find();
				if ($payRecord and $payRecord['channel'] != 'offline') {
					$order['payment_type'] = '线上支付';
				}else{
					$order['payment_type'] = '线下支付';
				}
			}
		}else{
			$order['payment_type'] = '未支付';
		}
		$order['payment_status'] = $order['payment_status'] == 1 ? '已付款' : '未付款';
		$order['payment_code'] = $this->payment[$order['payment_code']];

		if($order['service_status'] == 2) {   //退款凭证
			$order['voucher'] = $this->getVoucher($order['order_id']);
		}else{
			$order['voucher'] = null;
		}

		return $order;
	}

	//退款凭证
	public function getVoucher($orderId)
	{
		$model = M('WaterPurifierOrderCancel');
		$map['order_id'] = $orderId;
		$map['is_deleted'] = 0;
		$voucher = $model->field('amount,voucher,remark,pay_time')->where($map)->find();
		if ($voucher) {
			if ($voucher['voucher']) {
				$voucher['voucher'] = explode(',', $voucher['voucher']);
			}
			$voucher['pay_time'] = date('Y-m-d', $voucher['pay_time']);
		}
		return $voucher;
	}


	//统计
	public function getStastics($data, $down = false)
	{
		$model = M('WaterPurifierOrder');
		$model->alias('o');
		$map['o.is_deleted'] = 0;
		$map['o.pay_time'] = array('gt', 0);
		//活动创建时间开始区间
		if (isset($data['start']) and $data['start']) {
			$map['o.add_time'][] = array('egt', strtotime($data['start'].' 00:00:00'));
		}
		//活动创建时间结束区间
		if (isset($data['end']) and $data['end']) {
			$map['o.add_time'][] = array('elt', strtotime($data['end'].' 23:59:59'));			
		}
		if (isset($data['brand']) and in_array($data['brand'], array(1,2,3))) {
			$map['o.brand'] = $data['brand'];
		}

		if (isset($data['keyword']) and $data['keyword'] !== '') {
			$model->join('__USER__ u ON u.user_id = o.user_id', 'LEFT');
			$where['u.user_name']       = array('LIKE', '%'.$data['keyword'].'%');
			$where['o.shipping_name'] 	= array('LIKE', '%'.$data['keyword'].'%');
			$where['o.order_num']  		= array('LIKE', '%'.$data['keyword'].'%');
			$where['o.shipping_tel'] 	= array('LIKE', '%'.$data['keyword'].'%');
			$where['_logic'] = 'or';
			$map['_complex'] = $where;
		}
		$field = array('SUM(actually_total)'=>'total','SUM(IF(order_status = 0,actually_total, 0))'=>'no_paid','SUM(IF(order_status = 1, actually_total, 0))'=>'is_paid');
		if ($down) {
			$field['shipping_name'] = 'name';
			$list = $model->field($field)->where($map)->group('o.user_id')->order('total desc')->select();
			$total = $page = array();
		}else{
			$total = $model->field($field)->where($map)->find();
			if (is_null($total['total'])) {
				$total['total'] = 0;
				$total['no_paid'] = 0;
				$total['is_paid'] = 0;
				$count = 0;
			}else{
				$count = $model->alias('o')->join('__USER__ u ON u.user_id = o.user_id', 'LEFT')
				       ->where($map)->count('DISTINCT o.user_id');
			}
			$pageSize = $data['page_size'] > 0 ? $data['page_size'] : 10;
			$pageIndex = $data['page'] > 0 ? $data['page'] : 1;
			$page = pagination($count,$pageSize,$pageIndex);
			if ($count > 0) {
				$field['shipping_name'] = 'name';
				$field['user_name'] = 'user_name';
				$field['o.user_id'] = 'user_id';
				$list = $model->alias('o')->join('__USER__ u ON u.user_id = o.user_id', 'LEFT')
				      ->field($field)->where($map)->group('o.user_id')
				      ->order('total desc')
				      ->limit($page['offset'], $page['limit'])->select();
			}else{
				$list = array();
			}
		}
		return array('total'=>$total,'data'=>$list,'page'=>$page);
	

	}

	public function remark($orderId, $remark)
	{
		$model = M('WaterPurifierOrder');
		if ($orderId <= 0) {
			$this->setErrMsg(10001, '订单ID错误');
			return false;
		}
		$order = $model->find($orderId);
		if (!$order) {
			$this->setErrMsg(20001, '订单不存在');
			return false;
		}
		$data['order_id'] = $orderId;
		$data['remark'] = $remark;
		$res = $model->save($data);
		if ($res) {
			return true;
		}else{
			$this->setErrMsg(50000, '添加备注失败');
			return false;
		}
	}

	/**
	 * 取消订单
	 * @param  array $data 取消订单参数
	 * @return [type]          [description]
	 */
	public function orderCancel($data)
	{
		//参数验证
		if (!isset($data['order_id']) or $data['order_id'] <= 0) {
			$this->setErrMsg(10001, '订单ID错误');
			return false;
		}
		if (!isset($data['pay_time']) or $data['pay_time'] == '') {
			$this->setErrMsg(10001, '退款时间错误');
			return false;
		}
		$data['pay_time'] = strtotime($data['pay_time']);
		if ($data['pay_time'] > time()) {
			$this->setErrMsg(10001, '退款时间不能大于当前时间');
			return false;
		}

		if (!isset($data['remark']) or $data['remark'] == '') {
			$this->setErrMsg(10001, '退款备注不能为空');
			return false;
		}
		if (mb_strlen($data['remark']) > 200) {
			$this->setErrMsg(10001, '备注字数过多');
			return false;
		}

		if (isset($data['voucher']) and !empty($data['voucher'])) {
			if (!is_array($data['voucher'])) {
				$this->setErrMsg(10001, '凭证参数错误');
				return false;
			}
			if (count($data['voucher']) > 4) {
				$this->setErrMsg(10001, '订单凭证不能超过4张');
				return false;
			}
			foreach ($data['voucher'] as $k => $v) {
				if (empty($v) or strpos($v, 'http')) {
					$this->setErrMsg(10001, '凭证格式错误');
					return false;
				}
			}
			$data['voucher'] = implode(',', $data['voucher']);
		}else{
			$data['voucher'] = '';
		}

		//验证订单
		$orderModel = M('WaterPurifierOrder');
		$map['order_id'] = $data['order_id'];

		$order = $orderModel->where($map)->find();
		if (!$order) {
			$this->setErrMsg(20001, '订单不存在');
			return false;
		}
		if ($order['order_status'] == 0) {
			$this->setErrMsg(20002, '订单已取消，无须重复操作');
			return false;
		}
		$payTime = date('Y-m-d', $order['pay_time']);
		$payTime = strtotime($payTime);

		if ($data['pay_time'] < $payTime) {
			$this->setErrMsg(10001, '退款时间不能小于订单支付时间');
			return false;
		}
		//更新订单
		$save['order_id'] = $data['order_id'];
		$save['order_status'] = 0;
		$save['cancel_time'] = time();
		$orderModel->startTrans();
		$res = $orderModel->save($save);
		if ($res) {
			//插入取消订单详情
			$data['add_time'] = time();
			$data['order_type'] = $order['order_type'];
			$data['user_id'] = $order['user_id'];
			$data['amount'] = $order['actually_total'];
			$insert = M('WaterPurifierOrderCancel')->add($data);
			
		}else{
			$orderModel->rollback();
			$this->setErrMsg(50000, '取消订单失败');
		}

		//插入退款记录
		$payModel = M('UserPayRecord');
  		$payMap['order_id'] = $order['order_num'];
  		$payMap['event'] = 2;
  		$payMap['user_id'] = $order['user_id'];
  		$payRecord = $payModel->where($payMap)->find();

  		$payData['user_id'] = $order['user_id'];
  		$payData['subject'] = '净水器订单 -- '.'即时下单';
  		$payData['body'] = $payData['subject'];
  		$payData['total'] = $order['total'] * 100;
  		$payData['amount'] = $order['actually_total'] * 100;
  		$payData['order_no'] = strtoupper(md5(uniqid(mt_rand(), true)));
  		$payData['order_id'] = $order['order_num'];
  		$payData['extra'] = serialize(array());
  		$payData['channel'] = 'offline';
  		$payData['created'] = $data['pay_time'];
  		$payData['event'] = 2;
  		$payData['client_ip'] = $_SERVER['REMOTE_ADDR'];
  		$payData['order_type'] = 4;
  		$payData['status'] = 1;
  		$payData['addtime'] = time();
  		if($payRecord){
	  		$payRes = $payModel->where($payMap)->save($payData);
  		}else{
  			$payRes = $payModel->add($payData);
  		}

  		if ($insert and $payRes !== false) {
  			$orderModel->commit();
  			return true;
  		}else{
  			$orderModel->rollback();
  			$this->setErrMsg(50000, '取消订单失败');
  			return false;
  		}
	}

	
  	public function getPayRecord($data, $down = false)
  	{
  		$model = M('UserPayRecord');
  		$model->alias('r');
  		$model->join('__WATER_PURIFIER_ORDER__ o ON o.order_num = r.order_id', 'LEFT');
  		$map['r.order_type'] = 4;
  		if (isset($data['start']) and $data['start'] != '') {
  			$map['r.addtime'][] = array('egt', strtotime($data['start'].' 00:00:00'));
  		}
  		if (isset($data['end']) and $data['end'] != '') {
  			$map['r.addtime'][] = array('elt', strtotime($data['end'].' 23:59:59'));
  		}
  		if (isset($data['brand']) and in_array($data['brand'], array(1,2,3))){
  			$map['o.brand'] = $data['brand'];
  		}
  		if (isset($data['keyword']) and $data['keyword'] != '') {
  			$model->join('__USER__ u ON u.user_id = r.user_id', 'LEFT');
  			$where['u.user_name'] = array('LIKE', '%'.$data['keyword'].'%');
  			$where['order_id'] = array('LIKE', '%'.$data['keyword'].'%');
  			$where['_logic'] = 'or';
  			$map['_complex'] = $where;
  		}
  		if(isset($data['payment']) and in_array($data['payment'], array(1, 2))){
  			if ($data['payment'] == 1) { //线下支付
  				$map['channel'] = 'alipay';
  			}else{ //线上支付 channel 1 alipay 2 wx
  				$map['channel'] = array('neq', 'offline');
  			}
  		}
  		if (isset($data['type']) and in_array($data['type'], array(1, 2))) {
  			$map['event'] = $data['type'];
  		}
  		$total = $model->where($map)->count();
  		$pageSize = $data['page_size'] > 0 ? $data['page_size'] : 10;
		$pageIndex = $data['page'] > 0 ? $data['page'] : 1;
		$page = pagination($total,$pageSize,$pageIndex);
		if ($total > 0) {
			$list = $model->alias('r')
			->field('r.order_id,r.addtime,u.user_name,r.channel,r.amount,r.event,o.brand')
			->join('__USER__ u ON u.user_id = r.user_id', 'LEFT')
			->join('__WATER_PURIFIER_ORDER__ o ON o.order_num = r.order_id', 'LEFT')
			->where($map)->order('r.addtime desc');
			if($down){
				$list = $list->select();
			}else{
				$list = $list->limit($page['offset'], $page['limit'])->select();
				
			}
			foreach ($list as $k => $v) {
				$list[$k]['addtime'] = date('Y-m-d H:i:s', $v['addtime']);
				$list[$k]['amount'] = number_format($v['amount'] / 100, 2);
				$list[$k]['brand'] = $this->brand[$v['brand']];

				if ($v['event'] == 1) {
					$list[$k]['type'] = '收入';
				}else{
					$list[$k]['type'] = '支出';
				}

				$list[$k]['account'] = '净水器';
				if ($v['channel'] == 'alipay') {
				//	$list[$k]['payment'] = '线下支付';
					$list[$k]['channel'] = '支付宝';
				}elseif($v['channel'] == 'wx'){
					$list[$k]['channel'] = '微信';
				//	$list[$k]['payment'] = '在线支付';
				}else{
					$list[$k]['channel'] = '线下支付';
				}
			}
		}else{
			$list = array();
		}
		return array('data'=>$list,'page'=>$page);
  	}

  	//后台确认完成订单
  	public function finishOrder($orderId, $adminId)
  	{
  		$orderModel = M('WaterPurifierOrder');
        $map['order_id'] = $orderId;
        $map['order_status'] = 1;
        $map['is_deleted'] = 0;
        $order = $orderModel->where($map)->find();
        if(!$order){
            $this->setErrMsg('20001', '订单不存在');
            return false;
        }
        if ($order['finish_time'] > 0) {
            $this->setErrMsg('20002', '订单已完成，无须重复操作');
            return false;
        }
        $data['finish_time'] = time();
        $data['finish_type'] = 2;
        $data['finish_user_id'] = $adminId;
        $res = $orderModel->where($map)->save($data);
        return $res;
  	}


  	public function offlinePay($orderId, $adminId)
  	{
  		$orderModel = M('WaterPurifierOrder');
  		$orderMap['order_id'] = $orderId;
  		$orderMap['status'] = 1;
  		$orderMap['is_deleted'] = 0;
  		$order = $orderModel->where($orderMap)->find();
  		if (!$order) {
  			$this->setErrMsg(20001, '订单不存在');
  			return false;
  		}
  		$payModel = M('UserPayRecord');
  		$payMap['order_id'] = $order['order_num'];
  		$payRecord = $payModel->where($payMap)->find();
  		if ($order['pay_time'] > 0 and $payRecord and $payRecord['status'] == 1) {
  			$this->setErrMsg(20002, '订单已支付，无须操作');
  			return false;
  		}
  		$data['user_id'] = $order['user_id'];
  		$data['subject'] = '净水器订单 -- '.'即时下单';
  		$data['body'] = $data['subject'];
  		$data['total'] = $order['total'] * 100;
  		$data['amount'] = $order['actually_total'] * 100;
  		$data['order_no'] = strtoupper(md5(uniqid(mt_rand(), true)));
  		$data['order_id'] = $order['order_num'];
  		$data['extra'] = serialize(array());
  		$data['channel'] = 'offline';
  		$data['created'] = time();
  		$data['event'] = 1;
  		$data['client_ip'] = $_SERVER['REMOTE_ADDR'];
  		$data['order_type'] = 4;
  		$data['status'] = 1;
  		$data['addtime'] = time();
 	
  		$orderData['pay_time'] = time();
  		$orderData['payment_status'] = 1;
  		$orderData['finish_time'] = time();
  		$orderData['finish_type'] = 2;
  		$orderData['finish_user_id'] = $adminId;
  
  		$orderModel->startTrans();
  		$res = $orderModel->where($orderMap)->save($orderData);
  		if (!$res) {
  			$orderModel->rollback();
  			$this->setErrMsg(50000, '更新订单状态失败');
  			return false;
  		}
  		if ($payRecord) {
  			unset($data['order_num']);
  			$res = $payModel->where($payMap)->save($data);
  		}else{
  			$res = $payModel->add($data);
  		}
  		if (!$res) {
  			$orderModel->rollback();
  			$this->setErrMsg(50000, '插入支付记录失败');
  			return false;
  		}
  		$orderModel->commit();
  		return true;
  	}
}
?>